#include "../Source/server.hpp"

// 管理所有连接对象
std::unordered_map<uint64_t, PtrConnection> _conns;
uint64_t conn_id = 0;
    
EventLoop base_loop;
LoopThreadPool *loop_pool;

void ConnectionDestory(const PtrConnection &conn)
{
    DBG_LOG("Connection Destory");
    _conns.erase(conn->Id());
}
void OnConnected(const PtrConnection &conn)
{
    DBG_LOG("New Connection:%p", conn.get());
}
void OnMessage(const PtrConnection &conn, Buffer *buf)
{
    DBG_LOG("%s", (buf->GetReadPosition()));
    buf->MoveReadOffset(buf->ReadAbleSize());
    std::string str = "Hello World!";
    conn->Send(str.c_str(), str.size());
}

void NewConnection(int fd)
{
    conn_id++;
    PtrConnection conn(new Connection(loop_pool->NextLoop(), conn_id, fd));
    conn->SetMessageCallBack(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));
    conn->SetSrvClosedCallBack(std::bind(ConnectionDestory, std::placeholders::_1));
    conn->SetConnectedCallBack(std::bind(OnConnected, std::placeholders::_1));
    // 非活跃连接释放任务
    conn->EnableInactiveRelease(2);
    conn->Established();
    _conns.insert(std::make_pair(conn_id, conn));
    DBG_LOG("Accept A New Connection");
}

int main()
{

    loop_pool = new LoopThreadPool(&base_loop);
    // loop_pool->SetThreadCount(2);
    // loop_pool->Create();

    Acceptor acceptor(&base_loop, 8500);
    acceptor.SetAcceptCallBack(std::bind(NewConnection, std::placeholders::_1));
    acceptor.Listen();
    base_loop.Start();
}